using System.ComponentModel;
using System.Windows.Forms;
using BizTalk.BuildGenerator.UI.Navigation;

namespace BizTalk.BuildGenerator.UI.UserControls
{
    public partial class GenerateFilesControl : UserControl, IWizardControl
    {
        public delegate void GenerationCompleteDelegate();

        public event GenerationCompleteDelegate GenerationComplete;


        private GenerationArgs _Args;


        public GenerateFilesControl()
        {
            InitializeComponent();
        }

        public void RegisterArgs(GenerationArgs args)
        {
            _Args = args;
        }

        #region IWizardControl Members

        public MoveNextResult MoveNext()
        {
            backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += new DoWorkEventHandler(this.backgroundWorker_DoWork);
            backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(this.backgroundWorker_ProgressChanged);
            backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.backgroundWorker_RunWorkerCompleted);
            backgroundWorker.WorkerReportsProgress = true;
            backgroundWorker.RunWorkerAsync(_Args);
            MoveNextResult result = new MoveNextResult();
            result.CanMoveNext = false;
            return result;
        }

        #endregion

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BuildProcessController.ProcessUpdate += new BuildProcessController.BuildProcessUpdate(UpdateProgress);
            BuildProcessController.FullBuild((GenerationArgs) e.Argument);
        }

        private void UpdateProgress(int percentageComplete)
        {
            backgroundWorker.ReportProgress(percentageComplete);
        }


        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            StatusProgressBar.Value = e.ProgressPercentage;
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.ToString());
            }
            if (GenerationComplete != null)
                GenerationComplete();
        }
    }
}